
import Head from 'next/head'

<Head>
  <script>
    {
      `(function() {
         var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?e60fb290e204e04c5cb6f79b0ac1e697";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
       })();`
    }
  </script>
</Head>

![LangChain](https://pica.zhimg.com/50/v2-56e8bbb52aa271012541c1fe1ceb11a2_r.gif)







BabyAGI带工具[#](#babyagi-with-tools "此标题的永久链接")
===========





本文档基于[baby agi](baby_agi.html)，，但演示了如何更换执行链。之前的执行链只是一个LLM，胡编乱造。通过用具有工具访问权限的代理替换它，我们可以希望获得真正可靠的信息

安装和导入所需模块[#](#install-and-import-required-modules "此标题的永久链接")
-------------------------





```python

import os

from collections import deque

from typing import Dict, List, Optional, Any



from langchain import LLMChain, OpenAI, PromptTemplate

from langchain.embeddings import OpenAIEmbeddings

from langchain.llms import BaseLLM

from langchain.vectorstores.base import VectorStore

from pydantic import BaseModel, Field

from langchain.chains.base import Chain



```


### 连接到向量存储[#](#connect-to-the-vector-store "此标题的永久链接")




根据您使用的向量存储方式，此步骤可能看起来不同。




```python

%pip install faiss-cpu > /dev/null

%pip install google-search-results > /dev/null

from langchain.vectorstores import FAISS

from langchain.docstore import InMemoryDocstore



```



```python

# Define your embedding model

embeddings_model = OpenAIEmbeddings()

# Initialize the vectorstore as empty

import faiss



embedding_size = 1536

index = faiss.IndexFlatL2(embedding_size)

vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})



```

定义链[#](#define-the-chains "此标题的永久链接")
-----------------





BabyAGI依赖于三个LLM链:




* 任务创建链以选择要添加到列表中的新任务
* 任务优先级链以重新设置任务优先级
* 执行链执行任务





注意: 在这本笔记中，执行链将会变成代理。




```python

class TaskCreationChain(LLMChain):

 """Chain to generates tasks."""



    @classmethod

    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:

 """Get the response parser."""

        task_creation_template = (

            "You are an task creation AI that uses the result of an execution agent"

            " to create new tasks with the following objective: {objective},"

            " The last completed task has the result: {result}."

            " This result was based on this task description: {task_description}."

            " These are incomplete tasks: {incomplete_tasks}."

            " Based on the result, create new tasks to be completed"

            " by the AI system that do not overlap with incomplete tasks."

            " Return the tasks as an array."

        )

        prompt = PromptTemplate(

            template=task_creation_template,

            input_variables=[

                "result",

                "task_description",

                "incomplete_tasks",

                "objective",

            ],

        )

        return cls(prompt=prompt, llm=llm, verbose=verbose)



```



```python

class TaskPrioritizationChain(LLMChain):

 """Chain to prioritize tasks."""



    @classmethod

    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:

 """Get the response parser."""

        task_prioritization_template = (

            "You are an task prioritization AI tasked with cleaning the formatting of and reprioritizing"

            " the following tasks: {task_names}."

            " Consider the ultimate objective of your team: {objective}."

            " Do not remove any tasks. Return the result as a numbered list, like:"

            " #. First task"

            " #. Second task"

            " Start the task list with number {next_task_id}."

        )

        prompt = PromptTemplate(

            template=task_prioritization_template,

            input_variables=["task_names", "next_task_id", "objective"],

        )

        return cls(prompt=prompt, llm=llm, verbose=verbose)



```



```python

from langchain.agents import ZeroShotAgent, Tool, AgentExecutor

from langchain import OpenAI, SerpAPIWrapper, LLMChain



todo_prompt = PromptTemplate.from_template(

    "You are a planner who is an expert at coming up with a todo list for a given objective. Come up with a todo list for this objective: {objective}"

)

todo_chain = LLMChain(llm=OpenAI(temperature=0), prompt=todo_prompt)

search = SerpAPIWrapper()

tools = [

    Tool(

        name="Search",

        func=search.run,

        description="useful for when you need to answer questions about current events",

    ),

    Tool(

        name="TODO",

        func=todo_chain.run,

        description="useful for when you need to come up with todo lists. Input: an objective to create a todo list for. Output: a todo list for that objective. Please be very clear what the objective is!",

    ),

]





prefix = """You are an AI who performs one task based on the following objective: {objective}. Take into account these previously completed tasks: {context}."""

suffix = """Question: {task}

{agent_scratchpad}"""

prompt = ZeroShotAgent.create_prompt(

    tools,

    prefix=prefix,

    suffix=suffix,

    input_variables=["objective", "task", "context", "agent_scratchpad"],

)



```





### 定义BabyAGI控制器[#](#define-the-babyagi-controller "Permalink to this headline")




BabyAGI将在一个（可能是无限循环的）循环中组合上面定义的链。




```python

def get_next_task(

    task_creation_chain: LLMChain,

    result: Dict,

    task_description: str,

    task_list: List[str],

    objective: str,

) -> List[Dict]:

 """Get the next task."""

    incomplete_tasks = ", ".join(task_list)

    response = task_creation_chain.run(

        result=result,

        task_description=task_description,

        incomplete_tasks=incomplete_tasks,

        objective=objective,

    )

    new_tasks = response.split("")

    return [{"task_name": task_name} for task_name in new_tasks if task_name.strip()]



```



```python

def prioritize_tasks(

    task_prioritization_chain: LLMChain,

    this_task_id: int,

    task_list: List[Dict],

    objective: str,

) -> List[Dict]:

 """Prioritize tasks."""

    task_names = [t["task_name"] for t in task_list]

    next_task_id = int(this_task_id) + 1

    response = task_prioritization_chain.run(

        task_names=task_names, next_task_id=next_task_id, objective=objective

    )

    new_tasks = response.split("")

    prioritized_task_list = []

    for task_string in new_tasks:

        if not task_string.strip():

            continue

        task_parts = task_string.strip().split(".", 1)

        if len(task_parts) == 2:

            task_id = task_parts[0].strip()

            task_name = task_parts[1].strip()

            prioritized_task_list.append({"task_id": task_id, "task_name": task_name})

    return prioritized_task_list



```



```python

def _get_top_tasks(vectorstore, query: str, k: int) -> List[str]:

 """Get the top k tasks based on the query."""

    results = vectorstore.similarity_search_with_score(query, k=k)

    if not results:

        return []

    sorted_results, _ = zip(\*sorted(results, key=lambda x: x[1], reverse=True))

    return [str(item.metadata["task"]) for item in sorted_results]





def execute_task(

    vectorstore, execution_chain: LLMChain, objective: str, task: str, k: int = 5

) -> str:

 """Execute a task."""

    context = _get_top_tasks(vectorstore, query=objective, k=k)

    return execution_chain.run(objective=objective, context=context, task=task)



```



```python

class BabyAGI(Chain, BaseModel):

 """Controller model for the BabyAGI agent."""



    task_list: deque = Field(default_factory=deque)

    task_creation_chain: TaskCreationChain = Field(...)

    task_prioritization_chain: TaskPrioritizationChain = Field(...)

    execution_chain: AgentExecutor = Field(...)

    task_id_counter: int = Field(1)

    vectorstore: VectorStore = Field(init=False)

    max_iterations: Optional[int] = None



    class Config:

 """Configuration for this pydantic object."""



        arbitrary_types_allowed = True



    def add_task(self, task: Dict):

        self.task_list.append(task)



    def print_task_list(self):

        print("\033[95m\033[1m" + "\*\*\*\*\*TASK LIST\*\*\*\*\*" + "\033[0m\033[0m")

        for t in self.task_list:

            print(str(t["task_id"]) + ": " + t["task_name"])



    def print_next_task(self, task: Dict):

        print("\033[92m\033[1m" + "\*\*\*\*\*NEXT TASK\*\*\*\*\*" + "\033[0m\033[0m")

        print(str(task["task_id"]) + ": " + task["task_name"])



    def print_task_result(self, result: str):

        print("\033[93m\033[1m" + "\*\*\*\*\*TASK RESULT\*\*\*\*\*" + "\033[0m\033[0m")

        print(result)



    @property

    def input_keys(self) -> List[str]:

        return ["objective"]



    @property

    def output_keys(self) -> List[str]:

        return []



    def _call(self, inputs: Dict[str, Any]) -> Dict[str, Any]:

 """Run the agent."""

        objective = inputs["objective"]

        first_task = inputs.get("first_task", "Make a todo list")

        self.add_task({"task_id": 1, "task_name": first_task})

        num_iters = 0

        while True:

            if self.task_list:

                self.print_task_list()



                # Step 1: Pull the first task

                task = self.task_list.popleft()

                self.print_next_task(task)



                # Step 2: Execute the task

                result = execute_task(

                    self.vectorstore, self.execution_chain, objective, task["task_name"]

                )

                this_task_id = int(task["task_id"])

                self.print_task_result(result)



                # Step 3: Store the result in Pinecone

                result_id = f"result_{task['task_id']}"

                self.vectorstore.add_texts(

                    texts=[result],

                    metadatas=[{"task": task["task_name"]}],

                    ids=[result_id],

                )



                # Step 4: Create new tasks and reprioritize task list

                new_tasks = get_next_task(

                    self.task_creation_chain,

                    result,

                    task["task_name"],

                    [t["task_name"] for t in self.task_list],

                    objective,

                )

                for new_task in new_tasks:

                    self.task_id_counter += 1

                    new_task.update({"task_id": self.task_id_counter})

                    self.add_task(new_task)

                self.task_list = deque(

                    prioritize_tasks(

                        self.task_prioritization_chain,

                        this_task_id,

                        list(self.task_list),

                        objective,

                    )

                )

            num_iters += 1

            if self.max_iterations is not None and num_iters == self.max_iterations:

                print(

                    "\033[91m\033[1m" + "\*\*\*\*\*TASK ENDING\*\*\*\*\*" + "\033[0m\033[0m"

                )

                break

        return {}



    @classmethod

    def from_llm(

        cls, llm: BaseLLM, vectorstore: VectorStore, verbose: bool = False, \*\*kwargs

    ) -> "BabyAGI":

 """Initialize the BabyAGI Controller."""

        task_creation_chain = TaskCreationChain.from_llm(llm, verbose=verbose)

        task_prioritization_chain = TaskPrioritizationChain.from_llm(

            llm, verbose=verbose

        )

        llm_chain = LLMChain(llm=llm, prompt=prompt)

        tool_names = [tool.name for tool in tools]

        agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)

        agent_executor = AgentExecutor.from_agent_and_tools(

            agent=agent, tools=tools, verbose=True

        )

        return cls(

            task_creation_chain=task_creation_chain,

            task_prioritization_chain=task_prioritization_chain,

            execution_chain=agent_executor,

            vectorstore=vectorstore,

            \*\*kwargs,

        )



```

### 运行BabyAGI[#](#run-the-babyagi "Permalink to this headline")




现在是时候创建BabyAGI控制器并观察它尝试完成您的目标了。



```python

OBJECTIVE = "Write a weather report for SF today"



```



```python

llm = OpenAI(temperature=0)



```



```python

# Logging of LLMChains

verbose = False

# If None, will keep on going forever

max_iterations: Optional[int] = 3

baby_agi = BabyAGI.from_llm(

    llm=llm, vectorstore=vectorstore, verbose=verbose, max_iterations=max_iterations

)



```



```python

baby_agi({"objective": OBJECTIVE})



```





```python



\*\*\*\*\*TASK LIST\*\*\*\*\*



1: Make a todo list



\*\*\*\*\*NEXT TASK\*\*\*\*\*



1: Make a todo list





> Entering new AgentExecutor chain...

Thought: I need to gather data on the current weather conditions in SF

Action: Search

Action Input: Current weather conditions in SF

Observation: High 67F. Winds WNW at 10 to 15 mph. Clear to partly cloudy.

Thought: I need to make a todo list

Action: TODO

Action Input: Write a weather report for SF today

Observation: 



1. Research current weather conditions in San Francisco

2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions

3. Analyze data to determine current weather trends

4. Write a brief introduction to the weather report

5. Describe current weather conditions in San Francisco

6. Discuss any upcoming weather changes

7. Summarize the weather report

8. Proofread and edit the report

9. Submit the report

Thought: I now know the final answer

Final Answer: A weather report for SF today should include research on current weather conditions in San Francisco, gathering data on temperature, humidity, wind speed, and other relevant weather conditions, analyzing data to determine current weather trends, writing a brief introduction to the weather report, describing current weather conditions in San Francisco, discussing any upcoming weather changes, summarizing the weather report, proofreading and editing the report, and submitting the report.



> Finished chain.



\*\*\*\*\*TASK RESULT\*\*\*\*\*



A weather report for SF today should include research on current weather conditions in San Francisco, gathering data on temperature, humidity, wind speed, and other relevant weather conditions, analyzing data to determine current weather trends, writing a brief introduction to the weather report, describing current weather conditions in San Francisco, discussing any upcoming weather changes, summarizing the weather report, proofreading and editing the report, and submitting the report.



\*\*\*\*\*TASK LIST\*\*\*\*\*



2: Gather data on temperature, humidity, wind speed, and other relevant weather conditions

3: Analyze data to determine current weather trends

4: Write a brief introduction to the weather report

5: Describe current weather conditions in San Francisco

6: Discuss any upcoming weather changes

7: Summarize the weather report

8: Proofread and edit the report

9: Submit the report

1: Research current weather conditions in San Francisco



\*\*\*\*\*NEXT TASK\*\*\*\*\*



2: Gather data on temperature, humidity, wind speed, and other relevant weather conditions





> Entering new AgentExecutor chain...

Thought: I need to search for the current weather conditions in SF

Action: Search

Action Input: Current weather conditions in SF

Observation: High 67F. Winds WNW at 10 to 15 mph. Clear to partly cloudy.

Thought: I need to make a todo list

Action: TODO

Action Input: Create a weather report for SF today

Observation: 



1. Gather current weather data for SF, including temperature, wind speed, humidity, and precipitation.

2. Research historical weather data for SF to compare current conditions.

3. Analyze current and historical data to determine any trends or patterns.

4. Create a visual representation of the data, such as a graph or chart.

5. Write a summary of the weather report, including key findings and any relevant information.

6. Publish the weather report on a website or other platform.

Thought: I now know the final answer

Final Answer: Today in San Francisco, the temperature is 67F with winds WNW at 10 to 15 mph. The sky is clear to partly cloudy.



> Finished chain.



\*\*\*\*\*TASK RESULT\*\*\*\*\*



Today in San Francisco, the temperature is 67F with winds WNW at 10 to 15 mph. The sky is clear to partly cloudy.



\*\*\*\*\*TASK LIST\*\*\*\*\*



3: Research current weather conditions in San Francisco

4: Compare the current weather conditions in San Francisco to the average for this time of year.

5: Identify any potential weather-related hazards in the area.

6: Research any historical weather patterns in San Francisco.

7: Analyze data to determine current weather trends

8: Include any relevant data from nearby cities in the report.

9: Include any relevant data from the National Weather Service in the report.

10: Include any relevant data from local news sources in the report.

11: Include any relevant data from online weather sources in the report.

12: Include any relevant data from local meteorologists in the report.

13: Include any relevant data from local weather stations in the report.

14: Include any relevant data from satellite images in the report.

15: Describe current weather conditions in San Francisco

16: Discuss any upcoming weather changes

17: Write a brief introduction to the weather report

18: Summarize the weather report

19: Proofread and edit the report

20: Submit the report



\*\*\*\*\*NEXT TASK\*\*\*\*\*



3: Research current weather conditions in San Francisco





> Entering new AgentExecutor chain...

Thought: I need to search for current weather conditions in San Francisco

Action: Search

Action Input: Current weather conditions in San Francisco

Observation: TodaySun 04/09 High 67 · 1% Precip. ; TonightSun 04/09 Low 49 · 9% Precip. ; TomorrowMon 04/10 High 64 · 11% Precip.

Thought: I now know the final answer

Final Answer: Today in San Francisco, the high temperature is 67 degrees with 1% chance of precipitation. The low temperature tonight is 49 degrees with 9% chance of precipitation. Tomorrow's high temperature is 64 degrees with 11% chance of precipitation.



> Finished chain.



\*\*\*\*\*TASK RESULT\*\*\*\*\*



Today in San Francisco, the high temperature is 67 degrees with 1% chance of precipitation. The low temperature tonight is 49 degrees with 9% chance of precipitation. Tomorrow's high temperature is 64 degrees with 11% chance of precipitation.



\*\*\*\*\*TASK ENDING\*\*\*\*\*





```

```python

{'objective': 'Write a weather report for SF today'}



```



